import { Button, Flex, Form, FormProps, Input, Layout, Slider, Space, Upload } from 'antd';
import { PlusOutlined, MinusCircleOutlined, UploadOutlined } from '@ant-design/icons'
import { Header } from '../../components/BackToRoot';
import { fileToBase64 } from '../../utils';
import { bangumiDB } from '../../service/bangumi-db';
import { RULE_INPUT_REQUIRED } from '../../constant';
import { AnyFunction } from '../../type';
import '../../common.scss';
import './index.scss';
import { PageLayout } from '../../components/PageLayout';

const sourcesValidateTrigger = ['onChange', 'onBlur'];
const sourcesItemRule = [
    {
        required: true,
        whitespace: true,
        message: "请输入资源的链接",
    },
];
const sourcesListRule = [
    {
        validator: async (_: any, sources: any[]) => {
            if (!sources || sources.length < 1) {
                return Promise.reject(new Error('请至少录入一个资源'));
            }
        },
    },
];
const publishTimeRule = [{
    required: true,
    validator: (_: any, value: string) => {
        if (/\d{4}-\d{2}-\d{2}/.test(value)) {
            return Promise.resolve();
        }
        return Promise.reject(new Error('请按xxxx-xx-xx的格式输入'));
    }
}]

const labelCol = { span: 3, offset: 0 };

const onFinish: FormProps['onFinish'] = async (values) => {
    // img to base64
    const img = await fileToBase64(values.avatar.file.originFileObj);
    delete values.avatar;
    values.avatar = img;
    // 首播时间：为了后续可以用来排序所以转化为时间戳格式
    const timestamp = new Date(values.publishTime).getTime();
    values.publishTime = timestamp;
    bangumiDB.save(values.name, values);
};

const onFinishFailed: FormProps['onFinishFailed'] = (errorInfo) => {
    console.log('Failed:', errorInfo);
};

const sourcesList = (fields: any[], { add, remove }: { add: AnyFunction, remove: AnyFunction }, { errors }: { errors: any[] }) => (
    <>
        {fields.map((field, index) => (
            <Form.Item
                {...field}
                label={`资源${index + 1}`}
                required={true}
                key={field.key}
                validateTrigger={sourcesValidateTrigger}
                rules={sourcesItemRule}
                labelCol={labelCol}
            >
                <Flex gap={8}>
                    <Input placeholder="资源链接" />
                    {fields.length > 1 ? (
                        <MinusCircleOutlined
                            className="dynamic-delete-button"
                            onClick={() => remove(field.name)}
                        />
                    ) : null}
                </Flex>
            </Form.Item>
        ))}
        <Form.Item required={fields.length === 1} className="flex-center">
            <Button
                type="dashed"
                onClick={() => add()}
                style={{ width: 200 }}
                icon={<PlusOutlined />}
            >
                增加一个资源
            </Button>
            <Form.ErrorList errors={errors} />
        </Form.Item>
    </>
)

function RecordPage() {
    return <PageLayout >
        <Header />
        <Form labelCol={labelCol} onFinish={onFinish} onFinishFailed={onFinishFailed} initialValues={{ stars: 5 }} className='form'>
            <Form.Item name="name" label="番剧名称" rules={RULE_INPUT_REQUIRED}>
                <Input />
            </Form.Item>
            <Form.Item name="author" label="总监督" rules={RULE_INPUT_REQUIRED}>
                <Input />
            </Form.Item>
            <Form.Item name="publishTime" label="首播时间" rules={publishTimeRule}>
                <Input />
            </Form.Item>
            <Form.Item name="readCount" label="已看次数" rules={RULE_INPUT_REQUIRED}>
                <Input />
            </Form.Item>
            <Form.Item name="stars" label="评分" rules={RULE_INPUT_REQUIRED}>
                <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
                    0
                    <Slider max={5} min={0} step={0.1} className='slider' />
                    5.0
                </div>
            </Form.Item>
            <Form.Item name="country" label="国家" rules={RULE_INPUT_REQUIRED}>
                <Input />
            </Form.Item>
            <Form.Item name="lastProgress" label="上次进度" rules={RULE_INPUT_REQUIRED}>
                <Input />
            </Form.Item>
            <Form.List
                name="sources"
                rules={sourcesListRule}
            >
                {sourcesList}
            </Form.List>
            <Form.Item name="series" label="所属系列">
                <Input />
            </Form.Item>
            <Form.Item name="company" label="制作公司">
                <Input />
            </Form.Item>
            <Form.Item name="avatar" label="头像" rules={[{ required: false }]}>
                <Upload>
                    <Button icon={<UploadOutlined />}>Click to Upload</Button>
                </Upload>
            </Form.Item>
            <Form.Item name="note" label="备注" rules={[{ required: false }]}>
                <Input />
            </Form.Item>
            <Form.Item>
                <Flex justify='center'>
                    <Button type="primary" htmlType="submit">
                        保存
                    </Button>
                </Flex>
            </Form.Item>
        </Form>
    </PageLayout>
}

export default RecordPage;